#!/usr/bin/env python

from urlparse import parse_qs

from request import Request
from response import Response

class Mwe ( object ):

	def __init__ ( self, environ, start_response ):
		self.request = Request ( environ )
		self.response = Response ( start_response )
		
	def _handle ( self ):
		buf = []
		tokens = self.request.headers [ 'PATH_INFO' ].split ( '/' ) [ 1 : ]
		
		module_name = tokens [ 0 ]
		if not module_name: module_name = 'index'
		
		if len ( tokens ) == 1:
			func_name = 'index'
		else:
			func_name = tokens [ 1 ]
		if not func_name: func_name = 'index'
		
		args = tokens [ 2 : ]
		kwargs = parse_qs ( self.request.headers [ 'QUERY_STRING' ] )
		
		output = ''
		
		try:
			print 
			class_name = ''.join ( map ( str.title, module_name.split ( '_' ) ) )
			module = __import__ ( "modules.%s.%s" % ( module_name, module_name ), globals(), locals(), [], -1 )
			module = getattr ( module, module_name )
			module = getattr ( module, module_name )
			klass = getattr ( module, class_name )
			instance = klass()
			method = getattr ( instance, func_name )
			instance.predispatch()
			output = method ( self, *args, **kwargs )
			instance.postdispatch()
			
		except Exception as e:
			print e
			output = 'Internal server error'
		
		self.response.set_output ( output )
